<template>
  <div class="permission-grant-form">
    <h4>授予新权限</h4>
    <el-form :model="form" label-width="100px">
      <el-form-item label="选择用户" required>
        <el-select
            v-model="form.userId"
            placeholder="请选择用户"
            filterable
            style="width: 100%"
        >
          <el-option
              v-for="user in allUsers"
              :key="user.id"
              :label="`${user.username}`"
              :value="user.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="权限类型" required>
        <el-radio-group v-model="form.permissionType">
          <el-radio-button label="READ">只读</el-radio-button>
          <el-radio-button label="EDIT">可编辑</el-radio-button>
<!--          <el-radio-button label="MANAGE">可管理</el-radio-button>-->
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <el-button
            type="primary"
            :disabled="!canSubmit"
            :loading="submitting"
            @click="handleSubmit"
        >
          授予权限
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import {computed, onMounted, ref} from 'vue';
import type {GrantPermissionRequest, User} from "@/types";
import {grantPermission} from "@/api/permission.ts";
import {getUserId} from "@/utils/auth.ts";
import {ElMessage} from "element-plus";
import {getUserList} from "@/api/document.ts";

const props = defineProps<{
  currentPermissions?: Array<{ userId: string }>; // 现有权限列表(用于避免重复授权)
  documentId: string;
}>();

const emit = defineEmits<{
  (e: 'success'): void
  (e: 'error', error: Error): void
  (e: 'cancel'): void
}>()

// 表单数据
const form = ref({
  userId: null as string | null,
  permissionType: 'READ' as GrantPermissionRequest['permissionType']
});

// 模拟可授权用户列表(实际项目中应从API获取)
const allUsers = ref<User[]>([])
// 加载状态
const loading = ref(false)
const error = ref<string | null>(null) // 错误信息
// const allUsers = ref([
//   { id: 2, name: '张三', email: 'zhangsan@example.com' },
//   { id: 3, name: '李四', email: 'lisi@example.com' },
//   { id: 4, name: '王五', email: 'wangwu@example.com' },
// ]);

// 获取用户列表的函数
const fetchUsers = async () => {
  console.log('fetchUsers called'); // 检查是否执行
  loading.value = true
  error.value = null
  try {
    const currentUserId = getUserId() // 替换为实际获取用户ID的逻辑
    allUsers.value = await getUserList(currentUserId || '') // 直接赋值（假设接口返回User[]）
    console.log(allUsers.value)
  } catch (err) {
    error.value = '获取用户列表失败'
    console.error('Error fetching users:', err)
  } finally {
    loading.value = false
  }
}

// 在组件初始化时调用
onMounted(() => {
  fetchUsers()
})

// 提交状态
const submitting = ref(false)

// 检查是否可以提交
const canSubmit = computed(() => {
  return !!form.value.userId && !submitting.value;
});

// 提交表单
const handleSubmit = async () => {
  try {
    submitting.value = true;
    const payload: GrantPermissionRequest = {
      userId: form.value.userId || '',
      documentId: props.documentId,
      permissionType: form.value.permissionType,
      grantedBy: getUserId() || ''
    };
    await grantPermission(payload);
    ElMessage.success('授权成功');
    emit('success');
    resetForm()
    console.log("success")
  } catch (error) {
    ElMessage.error('授权失败');
  } finally {
    submitting.value = false;
  }
};

// 重置表单
const resetForm = () => {
  form.value = {
    userId: '',
    permissionType: 'READ'
  }
}
</script>

<style scoped>
.permission-grant-form {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
</style>